package com.example.demo.controller;

import com.example.demo.bean.User;
import com.example.demo.bean.UserInfo;
import com.example.demo.dao.UserMapper;
import com.example.demo.service.MailService;
import com.example.demo.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@CrossOrigin
@RequestMapping("/mail")
public class MailController {
    @Autowired
    private MailService mailService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisUtils redisUtils;
    /*
    * 发送邮箱验证码
    * */
    @RequestMapping("/getmailcode")
    @ResponseBody
    public String getmailcode(String mail){
        if(mailService.sendMimeMail(mail)){
            return "发送成功!";
        }else{
            return "发送失败!";
        }
    }
    /*
    * 检验验证码并注册!
    * */
    @RequestMapping("/register")
    @ResponseBody
    public String register(@RequestBody UserInfo userInfo){
        if(mailService.CheckCode(userInfo)){
            User user=userInfo.toUser();
            user.setImgurl("http://localhost:9090/images/default.jpg"); //默认头像!
            userMapper.register(user);
            redisUtils.set("user_"+user.getUsername(),user);//存入缓存!
            return "注册成功!";
        }else{
            return "验证码错误!";
        }
    }
    /*
     * 忘记密码
     * */
    @RequestMapping("/forgetpw")
    @ResponseBody
    public String forgetpw(@RequestBody UserInfo userInfo){
        if(mailService.CheckCode(userInfo)){
            User user=userInfo.toUser();
            int i=userMapper.forgetpw(user);
            if(i>0) {
                redisUtils.del("user_" + user.getUsername());       //直接把缓存删掉，防止登录时缓存数据不同步
                return "修改成功!";
            }else {
                return "邮箱或者用户名填写错误!";
            }
        }else{
            return "验证码错误!";
        }
    }
}
